import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:convert' as convert;

enum Action { Ok, Cancel }

class PrefUtil {
  static PrefUtil _manager;
  PrefUtil._internal();
  factory PrefUtil() => _sharedPreferences();
  static _sharedPreferences() {
    if (_manager == null) {
      _manager = PrefUtil._internal();
    }
    return _manager;
  }

  Future<bool> setString(String key, String value) async {
    var preferences = await SharedPreferences.getInstance();
    return preferences.setString(key, value);
  }

  Future<String> getString(String key) async {
    var preferences = await SharedPreferences.getInstance();
    return preferences.getString(key);
  }

  Future<bool> setBool(String key, bool value) async {
    var preferences = await SharedPreferences.getInstance();
    return preferences.setBool(key, value);
  }

  Future<bool> getBool(String key) async {
    var preferences = await SharedPreferences.getInstance();
    return preferences.getBool(key);
  }

  Future<bool> delete(String key) async {
    var preferences = await SharedPreferences.getInstance();
    return preferences.remove(key);
  }

  Future<bool> setTaskInfo(Map<String, dynamic> data) async {
    await setString('taskInfo', convert.jsonEncode(data));
    print(getString('taskInfo'));
    return true;
  }

  // 检验是否登录
  Future<bool> isLogin() async {
    var preferences = await SharedPreferences.getInstance();
    return preferences.getBool('isLogin') ?? false;
  }

  // 是否保存数据弹窗
  Future openAlertDialog(context, text) async {
    var result;
    final action = await showDialog(
      context: context,
      barrierDismissible: false, //// user must tap button!
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text('提示'),
          content: Text(text ?? '是否保存数据'),
          actions: <Widget>[
            FlatButton(
              child: Text('取消'),
              onPressed: () {
                Navigator.pop(context, Action.Cancel);
              },
            ),
            FlatButton(
              child: Text('确认'),
              onPressed: () {
                Navigator.pop(context, Action.Ok);
              },
            ),
          ],
        );
      },
    );

    switch (action) {
      case Action.Ok:
        result = 'ok';
        break;
      case Action.Cancel:
        result = 'cancel';
        break;
      default:
    }

    return result;
  }
}
